package com.huluobo.lib_base.mvvm

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.lib_base.event.MessageEvent
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.lang.reflect.ParameterizedType

/**
 *  Created by LC on 2025/9/15.
 */
abstract class BaseFragment<VDB : ViewDataBinding, VM : BaseViewModel> : Fragment() {
    //获取当前类的泛型的集合
    private val type by lazy { (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments }

    //拿到binding
    protected val binding: VDB by lazy {
        //获取第一个泛型,强转成一个ViewBinding的类
        val clazz = type[0] as Class<VDB>
        //通过反射的形式从LayoutInflater类中获取inflate的方法
        val method = clazz.getMethod("inflate", LayoutInflater::class.java)
        //调用一次inflate方法,直接把布局添加到页面上,形成一个自动获取的机制
        method.invoke(null, layoutInflater) as VDB
    }

    //拿到vm
    protected val vm: VM by lazy {
        //获取第二个泛型,强转成一个ViewModel的类
        val clazz = type[1] as Class<VM>
        //通过VM的提供者,来拿到第二个泛型,获取ViewModel的实现类
        //requireActivity 指向是当前Fragment的Activity,这样才能实现数据共享
        ViewModelProvider(requireActivity())[clazz]
    }

    //对外提供显示错误信息的方法
    open fun onError(t: Throwable) {
        //显示toast给用户看
        ToastUtils.showLong(t.message)
        //显示log给开发看
        Log.e("TagA", "onError:${t.message}")
        //打印一个完整异常
        t.printStackTrace()
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        vm.onFailed.observe(requireActivity(), ::onError)
        initView()
        initData()
        EventBus.getDefault().register(this)
    }

    abstract fun initData()

    abstract fun initView()

    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun onEvent(messageEvent: MessageEvent) {

    }
}